<template>
  <div>
    <el-dialog :close-on-click-modal="false" :title="stepdata.name" :visible.sync="dialogShow" customClass="flowChartDetails" width="900px" top="10vh">
      <el-tabs v-model="tabsModel" @tab-click="tabClick" v-show="!triggerShow.isShow">
        <el-tab-pane :label="$t('config.business.stepInfo')" name="first" v-if="isStep" class="tab-pane">
            <el-form label-position="top" :inline="true" class="el-row" >
              <el-form-item :label="$t('config.business.stepName')" class="el-col-7">
                <el-input v-model="stepdata.name" key="stepdata.name" :maxlength="10"></el-input>
              </el-form-item>
            <el-form-item :label="$t('config.business.taskTimeLimit')" class="el-col-7">
              <el-input v-model="stepdata.ctime" key="stepdata.ctime" :placeholder="$t('config.business.firstStepNotSet')" :maxlength="5"></el-input>
            </el-form-item>
            <el-form-item :label="$t('config.business.unit')" class="el-col-7">
              <el-select v-model="stepdata.ctype">
                <el-option :label="$t('public.minutes2')" value="min"></el-option>
                <el-option :label="$t('public.hours2')" value="hours"></el-option>
                <el-option :label="$t('public.day2')" value="day"></el-option>
              </el-select>
            </el-form-item>
            </el-form>
            <el-form label-position="top"  class="el-row">
              <el-form-item :label="$t('config.business.notifyUser')">
                <el-select multiple size="small" filterable v-model="stepdata.notifyUser" style="margin-right: 10px;width: 430px">
                  <el-option :label="$t('config.business.currentHandlerSuperior')" value="masterLeader"></el-option>
                  <el-option v-for="item in agentsList" :label="agentExten(item)" :value="item._id" :key="item._id"></el-option>
                  <el-option v-for="item in realAgentsList" :label="agentExten(item)" :value="item._id" :key="item._id" style="display:none;width:0;height:0"></el-option>
                </el-select>
                <el-tooltip effect="dark" placement="top" :content="$t('config.business.businessTip')">
                  <i class="iconfont icon-wenzishuoming add-flow-color"></i>
                </el-tooltip>
              </el-form-item>
              <el-form label-position="top" :inline="true"  class="el-row">
                <el-form-item :label="$t('config.business.isBegin')">
                  <el-radio-group v-model="stepdata.isBegin" disabled>
                    <el-radio :label="true">{{$t('public.yes')}}</el-radio>
                    <el-radio :label="false">{{$t('public.no')}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </el-form>
        </el-tab-pane>
        <el-tab-pane class="tab-pane" :label="$t('config.business.stepLayout')" name="second" v-if="isStep">
          <div class="stepLayout">
          <el-form :inline="true" label-position="top" v-if="customerFields.length > 0">
              <el-row :gutter="20" v-for="item in customerFields">
                <el-col v-for="col in item.cols" :span="24/item.cols.length">
                  <div v-for="one in col.fields">
                    <b-input v-if="one.type==='single'" disabled :label="one.name" :default="one.default" :id="one._id"></b-input>
                    <b-number v-if="one.type==='number'" disabled :label="one.name" :default="one.default" :id="one._id"></b-number>
                    <b-textarea v-if="one.type==='multi'" disabled :label="one.name" :default="one.default" :id="one._id"></b-textarea>
                    <b-radio v-if="one.type==='radio'" disabled :label="one.name"  :dic="one.dic" :default="one.default" :id="one._id" :field="one"></b-radio>
                    <b-checkbox v-if="one.type==='checkbox'" disabled :label="one.name" :dic="one.dic" :default="one.default" :id="one._id" :field="one"></b-checkbox>
                    <b-datatime v-if="one.type==='date' || one.type==='datetime'" disabled :label="one.name"  :default="one.default" :id="one._id"></b-datatime>
                    <b-time v-if="one.type==='time'" disabled :label="one.name"  :default="one.default" :id="one._id"></b-time>
                    <b-select v-if="one.type==='dropdown'" disabled :label="one.name" :dic="one.dic"  :default="one.default" :id="one._id" :field="one"></b-select>
                    <b-tree v-if="one.type==='dropdownTree'" disabled :label="one.name" :dic="one.dic"  :default="one.default" :id="one._id" :field="one"></b-tree>
                    <b-file v-if="one.type==='file'" disabled :label="one.name" :default="[]" :id="one._id"></b-file>
                  </div>
                </el-col>
              </el-row>
          </el-form>
            <p class="noFieldTip font16" v-else>
              该步骤未配置步骤界面
            </p>
          </div>
        </el-tab-pane>
        <el-tab-pane class="tab-pane" :label="$t('config.business.stepsDocking')" name="interface" v-if="isStep && stepinfo.type !=='sys'">
          <el-form label-position="top" ref="form" :model="interface" :rules="rules" class="form">
            <affix :label="$t('config.business.outDocking')">
              <el-form-item label="url" prop="outflowUrl">
                <el-input v-model.trim="interface.outflowUrl">
                </el-input>
              </el-form-item>
              <span class="help-tips font12">http://company.com/?固定字段信息（可能是客户的工单类型信息）</span>
              <el-form-item :label="$t('config.business.stepAction')">
                <el-select v-model="interface.actionId" :placeholder="$t('public.pleasePick')" @change="actionChange">
                  <el-option
                    :value="''"
                    :label="$t('public.pleasePick')"
                  ></el-option>
                  <el-option
                  v-for="(item,index) in stepinfo.actions"
                  :key='index'
                  :value="item._id"
                  :label="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <div class="code">
                {
                _id: 'xxxxxxx',//工单id<br>
                fields:[<br>
                <template v-for="(one, index) in interface.fields">
                  {name: '{{one.name}}',type: '{{one.type}}',value: {{one.value}}}
                  {{index+1 !== interface.fields.length? ',': ''}}
                  <br>
                </template>
                ],<br>
                user: '工号',//处理人<br>
                createTime: 'yyyy-mm-dd HH:mm:ss',<br>
                flowInfo: '步骤信息',<br>
                action: '{{interface.actionName}}',//动作名称<br>
                createTimestamp: 1505716040000//创建时间毫秒数<br>
                priority: '1' // 工单优先级，创建工单时可传'1'，'2','3'表示普通，紧急，很紧急<br>
                }
              </div>
            </affix>
            <affix :label="$t('config.business.intoDocking')">
              <el-form-item label="url" >
                <div class="font12 inflow-url">{{interface.inflowUrl}}</div>
              </el-form-item>
              <div class="code">
                {
                _id: '工单id',// 工单id、工单编号如果均为空则表示新建工单<br>
                number: '工单编号',// 工单id、工单编号如果均为空则表示新建工单<br>
                customerId: '客户id',// 如果为空则表示未知客户<br>
                fields:[<br>
                <template v-for="(one, index) in interface.fields">
                  {name: '{{one.name}}',type: '{{one.type}}',value: {{one.value}}}
                  {{index+1 !== interface.fields.length? ',': ''}}{{one.required === 'required'? '//必传': ''}}
                  <br>
                </template>
                ],<br>
                targetUser: '工号|auto',// 指派给谁处<br>
                createUser: '工号',<br>
                flowName: '工单流名称',// 必传<br>
                comment: '备注',<br>
                stepName: '工单步骤名称',// 必传<br>
                action: '{{interface.actionName}}', // 动作名称<br>
                priority: '1' // 工单优先级，创建工单时可传'1'，'2','3'表示普通，紧急，很紧急<br>
                }
              </div>
            </affix>
          </el-form>
        </el-tab-pane>
        <el-tab-pane  class="tab-pane" :label="$t('config.business.actionLayout')" name="first" v-if="!isStep">
          <el-form :inline="true" label-position="top"  v-if="customerFields.length > 0">
            <el-row :gutter="20" v-for="item in customerFields">
              <el-col v-for="col in item.cols" :span="24/item.cols.length">
                <div v-for="one in col.fields">
                  <b-input v-if="one.type==='single'" disabled :label="one.name" :default="one.default" :id="one._id"></b-input>
                  <b-number v-if="one.type==='number'" disabled :label="one.name" :default="one.default" :id="one._id"></b-number>
                  <b-textarea v-if="one.type==='multi'" disabled :label="one.name" :default="one.default" :id="one._id"></b-textarea>
                  <b-radio v-if="one.type==='radio'" disabled :label="one.name"  :dic="one.dic" :default="one.default" :id="one._id" :field="one"></b-radio>
                  <b-checkbox v-if="one.type==='checkbox'" disabled :label="one.name" :dic="one.dic" :default="one.default" :id="one._id" :field="one"></b-checkbox>
                  <b-datatime v-if="one.type==='date' || one.type==='datetime'" disabled :label="one.name"  :default="one.default" :id="one._id"></b-datatime>
                  <b-time v-if="one.type==='time'" disabled :label="one.name"  :default="one.default" :id="one._id"></b-time>
                  <b-select v-if="one.type==='dropdown'" disabled :label="one.name" :dic="one.dic"  :default="one.default" :id="one._id" :field="one"></b-select>
                  <b-tree v-if="one.type==='dropdownTree'" disabled :label="one.name" :dic="one.dic"  :default="one.default" :id="one._id" :field="one"></b-tree>
                  <b-file v-if="one.type==='file'" disabled :label="one.name" :default="[]" :id="one._id"></b-file>
                </div>
              </el-col>
            </el-row>
          </el-form>
          <p class="noFieldTip font16" v-else>
            该动作未配置动作界面
          </p>
        </el-tab-pane>
        <el-tab-pane  class="tab-pane" :label="$t('config.business.trigger')" name="flowTrigger" v-if="isStep && !this.stepinfo.isBegin">
          <div class="prompt" v-html="$t('config.business.triggerWarmPrompt')"></div>
          <flow-trigger :currentStepInfo="stepinfo"
                        @openDialog="openTriggerForm"
                        ref="flowTrigger"></flow-trigger>
        </el-tab-pane>
      </el-tabs>
      <div v-show="triggerShow.isShow" style="padding: 0 20px" class="trigger-add">
        <bread-crumb :titleArr="triggerShow.name" @back="back" :font-size="14" style="padding: 8px 10px"></bread-crumb>
        <trigger-form :defaultAgent="defaultAgent" ref="triggerForm" :currentStep="stepinfo"></trigger-form>
      </div>
      <div slot="footer" style="text-align: center">
        <el-button class="primary_btn" @click="handleCancel">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="handleConfirm">{{$t('public.confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {deepClone, getCache} from '@/utils/m7Utils'
  import {getObjectById, getRoleAgents} from '@/utils/workflowUtils.js'
  import {checkform} from '@/utils/validate'
  import BInput from '@/components/public-modules/cust-tab-content/business/base/Binput.vue'
  import BTextarea from '@/components/public-modules/cust-tab-content/business/base/Btextarea.vue'
  import BRadio from '@/components/public-modules/cust-tab-content/business/base/Bradio.vue'
  import BCheckbox from '@/components/public-modules/cust-tab-content/business/base/Bcheckbox.vue'
  import BDatatime from '@/components/public-modules/cust-tab-content/business/base/Bdatatime.vue'
  import BTime from '@/components/public-modules/cust-tab-content/business/base/Btime.vue'
  import BSelect from '@/components/public-modules/cust-tab-content/business/base/Bselect.vue'
  import BTree from '@/components/public-modules/cust-tab-content/business/base/Btree.vue'
  import BFile from '@/components/public-modules/cust-tab-content/business/base/Bfile.vue'
  import BNumber from '@/components/public-modules/cust-tab-content/business/base/Bnumber.vue'
  import Affix from '../../../ui-modules/affix/Affix.vue'
  import flowTrigger from '../../newConfig/businessConfig/flowConfig/flowTrigger'
  import triggerForm from '../../newConfig/businessConfig/flowConfig/triggerForm'
  import breadCrumb from '../../../ui-modules/breadCrumb/BreadCrumbConfig'
  export default {
    components: {
      BInput,
      BTextarea,
      BRadio,
      BCheckbox,
      BDatatime,
      BSelect,
      BFile,
      BNumber,
      BTree,
      BTime,
      Affix,
      flowTrigger,
      triggerForm,
      breadCrumb
    },
    name: 'flowChartDetails',
    data () {
      let validate1 = (rule, value, callback) => {
        if (value === '' || !checkform(value, 'Url')) {
          callback()
        } else {
          callback(new Error('url格式错误'))
        }
      }
      return {
        dialogShow: false,
        tabsModel: 'first',
        stepdata: '',
        agentsList: [],
        realAgentsList: [],
        customerFields: [],
        nextAction: [],
        interface: {
          outflowUrl: '',
          inflowUrl: '',
          actionName: '',
          actionId: '',
          fields: []
        },
        rules: {
          outflowUrl: [
            {validator: validate1, trigger: 'blur'}
          ]
        },
        triggerShow: {
          isShow: '',
          type: '',
          name: [this.$t('config.business.triggerList'),this.$t('config.business.addTrigger')]
        },
        defaultAgent: []
      }
    },
    props: {
      stepinfo: {
      },
      stepfields: {
        default: []
      },
      flowData: {}
    },
    computed: {
      stepdata1 () {
        return this.stepinfo
      },
      isStep () {
        return this.stepinfo.actions !== undefined
      }
    },
    watch: {
      stepdata1 (newVal) {
        this.tabsModel = 'first'
        this.stepdata = deepClone(newVal)
        if (this.stepdata.notifyUser === undefined || this.stepdata.notifyUser === '') {
          this.$set(this.stepdata, 'notifyUser', [])
        } else if (typeof this.stepdata.notifyUser === 'string') {
          this.stepdata.notifyUser = this.stepdata.notifyUser.split(',')
        }
        if (!this.stepdata.ctime) {
          this.$set(this.stepdata, 'ctime', '')
        }
        if (!this.stepdata.ctype) {
          this.$set(this.stepdata, 'ctype', 'min')
        }
        this.formatBusinessStepfields()
        this.dialogShow = true
        this.triggerShow.isShow = false
      }
    },
    methods: {
      // 生成默认处理人
      async filterAgent () {
        let actions = this.stepinfo.actions || []
        let roles = []
        let queues = []
        for (let i = 0; i < actions.length; i++) {
          let actionsItem = actions[i]
          // 判断角色还是技能组
          if(actionsItem.actionAllow === 1){
            if(actionsItem.actionQueue.length>0){ // 技能组
              actionsItem.actionQueue.forEach(item=>{
                queues.push(item)
              })
            }
          } else {
            //兼容老数据，之前是字符串
            if(!Array.isArray(actionsItem.actionRole)){
              actionsItem.actionRole = [actionsItem.actionRole]
            }
            // 角色
            if(actionsItem.actionRole.length>0){
              actionsItem.actionRole.forEach(item=>{
                roles.push(item)
              })
            } 
          }
        }
        // 多个步骤动作，会存在角色和技能组同时存在的情况
        let queueAgentList = []
        let roleAgentList = []
        if(roles.length>0){
          roleAgentList = getRoleAgents(roles, false, 'busConfig') || []
        } 
        if (queues.length>0) {
          // 获取工单技能组
          queueAgentList = await getQueueAgents(queues, false)
        }
        let agents = [...new Set(roleAgentList.concat(queueAgentList))]
        let data = agents.map((item) => {
          let label = item.displayName
          // ‘工单创建人’没有exten
          if (item.exten) {
            label += `[${item.exten}]`
          }
          return {label, value: item._id, status:item.status }
        })
        this.defaultAgent = data
      },
      openTriggerForm (type, data) {
        this.triggerShow.isShow = true
         if (type === 'add') {
          this.$set(this.triggerShow,'name',[this.$t('config.business.triggerList'),this.$t('config.business.addTrigger')])
        } else {
          this.$set(this.triggerShow,'name',[this.$t('config.business.triggerList'),this.$t('config.business.editTrigger')])
        }
        this.triggerShow.type = type
        this.$refs.triggerForm.initForm(data)
      },
      back () {
        this.triggerShow.isShow = false
      },
      handleCancel () {
        if (this.triggerShow.isShow) {
          this.triggerShow.isShow = false
        } else {
          this.dialogShow = false
        }
      },
      parseIntTime (ctype, ctime) {
        let time = parseInt(ctime) || 0
        if (ctype === 'hours' || ctype === 'hour') {
          time = time * 60
        } else if (ctype === 'day') {
          time = time * 60 * 24
        }
        return time
      },
      formatBusinessStepfields () {
        this.customerFields = deepClone(this.stepdata1.stepFields || this.stepdata1.actionFields || [])
        let flowFields = this.stepfields
        for (let i = 0; i < this.customerFields.length; i++) {
          let row = this.customerFields[i]
          for (let j = 0; j < row.cols.length; j++) {
            let col = row.cols[j]
            for (let k = 0; k < col.fields.length; k++) {
              let field = col.fields[k]
              let cacheField = getObjectById(flowFields, field._id)
              if (cacheField.type === 'dropdown' || cacheField.type === 'dropdownTree') {
                cacheField['default'] = [cacheField['default'], '', '']
              } else if (cacheField.type === 'checkbox') {
                cacheField['default'] = [cacheField['default']]
              }
              Object.assign(field, cacheField)
            }
          }
        }
      },
      generateBusinessFieldsExample (fieldsData, flag) {
        let arr = []
        for (let i = 0; i < fieldsData.length; i++) {
          let item = fieldsData[i].cols
          for (let m = 0; m < item.length; m++) {
            let itemTwo = item[m].fields
            for (let n = 0; n < itemTwo.length; n++) {
              let itemThree = itemTwo[n]
              let field = getCache('businessFlowField', itemThree._id)
              if (field) {
                let type = field.type
                let result = {name: field.name, type: field.type, required: field.required}
                switch (type) {
                  case 'single':
                    result.value = '\'abc\''
                    break
                  case 'multi':
                    result.value = '\'abc\''
                    break
                  case 'date':
                    result.value = '\'YYYY-MM-DD\''
                    break
                  case 'time':
                    result.value = '\'HH:MM:SS\''
                    break
                  case 'datetime':
                    result.value = '\'YYYY-MM-DD HH:MM:SS\''
                    break
                  case 'number':
                    result.value = 1
                    break
                  case 'dropdown':
                    result.value = '[\'select1\']'
                    break
                  case 'dropdownTree':
                    result.value = '[\'select1\']'
                    break
                  case 'checkbox':
                    result.value = '[\'checkbox1\',\'checkbox2\',\'checkbox3\']'
                    break
                  case 'radio':
                    result.value = '\'abc\''
                    break
                  case 'file':
                    result.value = '[{name:\'123.jpg\',value:\'base64\u7801\'}]'
                    break
                  default :
                    console.log('the type [' + type + '] is not support!')
                }
                arr.push(result)
              }
            }
          }
        }
        return arr
      },
      agentExten (agent) {
        return agent.displayName + '[' + agent.exten + ']'
      },
      agentsChange () {
        this.$nextTick(function () {
          document.getElementsByClassName('el-select__input is-undefined')[0].value = ''
        })
      },
      isModify () {
        let name = (this.stepdata.name === this.stepinfo.name || this.stepinfo.name === undefined)
        let ctime = (this.stepdata.ctime === this.stepinfo.ctime || (this.stepdata.ctime === '' && this.stepinfo.ctime === undefined))
        let ctype = (this.stepdata.ctype === this.stepinfo.ctype || (this.stepinfo.ctype === 'min' && this.stepinfo.ctype === undefined))
        let infoNotifyUser = this.stepinfo.notifyUser || ''
        let a = this.stepdata.notifyUser.toString()
        let b = infoNotifyUser.toString()
        let notifyUser = (a === b)
        return (!name || !ctime || !ctype || !notifyUser)
      },
      handleConfirm () {
        if (this.tabsModel === 'interface') {
          this.$refs.form.validate((valid) => {
            if (valid) {
              this.$store.dispatch('updateBusinessStepAPI', {_id: this.stepinfo._id, outflowInterface: {url: this.interface.outflowUrl}}).then((response) => {
                if (response.success) {
                  this.$message.success(this.$t('保存成功'))
                  this.dialogShow = false
                }
              })
            }
          })
        } else if (this.tabsModel === 'flowTrigger' && this.triggerShow.isShow) {
          let data = this.$refs.triggerForm.submit()
          this.$refs.flowTrigger.save(this.triggerShow.type, data, () => {
            this.triggerShow.isShow = false
          })
        } else if (this.isStep && this.isModify()) {
          let data = deepClone(this.stepdata)
          let steptime = this.parseIntTime(data.ctype, data.ctime)
          let flowtime = this.parseIntTime(this.flowData.ctype, this.flowData.ctime)
          if (steptime > flowtime && flowtime > 0) {
            this.$message.error('单步骤时间不能超过工单总时长,请重新设置！')
            return
          }
          data.notifyUser = data.notifyUser.join(',')
          this.$store.dispatch('updateBusinessStepInfo', data).then((response) => {
            if (response.success) {
              this.$message.success(this.$t('config.business.updateBusinessFlowStepSuccess'))
              this.$emit('save')
              this.dialogShow = false
            }
          })
        } else {
          this.dialogShow = false
        }
      },
      actionChange (value) {
        let field = []
        if (this.stepinfo.isBegin) {
          field = this.generateBusinessFieldsExample(this.stepinfo.stepFields || [])
        }
        let action = this.stepinfo.actions || []
        this.interface.actionName = ''
        for (let i = 0; i < action.length; i++) {
          if (action[i]._id === value) {
            field = field.concat(this.generateBusinessFieldsExample(action[i].actionFields || []))
            this.interface.actionName = action[i].name
            break
          }
        }
        this.interface.fields = field
      },
      tabClick (tab) {
        if (tab.name === 'interface') {
          this.interface.actionId = ''
          this.actionChange('')
          this.$store.dispatch('getCache', {type: 'restApiUrl'}).then((res) => {
            if (res) {
              this.interface.inflowUrl = res[0].code_value.handleBusiness + '/' + this.$store.state.session.account.account + '?sig=xxxx'
            }
            this.interface.outflowUrl = this.stepinfo.outflowInterface ? this.stepinfo.outflowInterface.url : ''
          })
        } else if (tab.name === 'flowTrigger') {
          this.filterAgent()
          this.getAllFields()
          this.$refs.flowTrigger.initData()
        }
      },
      getAllFields () {
        this.$store.dispatch('queryAllBusinessFlowFields', {flow_id: this.stepinfo.flow_id}).then((res) => {
          this.$store.commit('flowConfig/UPDATE_FLOW_FIELD', {type: 'all', data: res.data, currentType: 'oldFlow'})
        })
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'agents'}).then((agents) => {
        agents.forEach(item=>{
          if(item.status == 'enable'){
            this.agentsList.push(item)
          }else{
            this.realAgentsList.push(item)
          }
        })
      })
      this.$store.dispatch('getCache', {type: 'businessFlowField'}).then((agents) => {
      })
    },
    deactivated () {
      this.dialogShow = false
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .el-form-item
    margin-bottom 0
  .add-flow-color
    color $c-main
    margin-bottom 10px
  .stepLayout
    .el-form--label-top .el-form-item__label
      font-size 16px
      padding 4px 0
  .noFieldTip
    text-align center
    margin-top 30px
  .code
    background-color #eee
    padding 10px
    line-height 18px
   .inflow-url
    color $c-main
    padding-bottom 10px
  .help-tips
    color #999
  .prompt
    color $c-prompt
    font-size 12px
    padding-bottom 20px
  .tab-pane
    max-height 45vh
    overflow-y auto
  .trigger-add
    max-height calc(45vh + 40px)
    overflow-y auto
</style>
